﻿using AiBLSmartEdu.Module.SmartDictionaries.API.DTOs;
using AiBLSmartEdu.Module.SmartDictonaries.API.DTOs;
using AutoMapper;
using Domain.Entities;
using FrameworkCore.DI;
using FrameworkCore.Extensions;
using FrameworkCore.Helpers;
using FrameworkCore.Models;
using FrameworkCore.Repositories;

namespace AiBLSmartEdu.Module.SmartDictionaries.API.Services;

#nullable disable

public class ChineseDictionaryServices : IScopedDependency
{
    private readonly IRepository<ChineseDictionary> __chineseDictionaryRepository;
    private readonly IMapper _mapper;
    private readonly DictionariesHelpers _dictionariesHelpers;

    public ChineseDictionaryServices(IRepository<ChineseDictionary> chineseDictionaryRepository, IMapper mapper, DictionariesHelpers dictionariesHelpers)
    {
        __chineseDictionaryRepository = chineseDictionaryRepository;
        _mapper = mapper;
        _dictionariesHelpers = dictionariesHelpers;
    }

    /// <summary>
    /// 分页查询
    /// </summary>
    /// <param name="filter">分页输入模型</param>
    /// <returns></returns>
    public async Task<PageResult<ChineseDictionaryOutputModel>> PageAsync(ChineseDictionaryPaginationFilter filter)
    {
        return (await __chineseDictionaryRepository.GetOrderedQueryable(query =>
        {
            return query.WhereIf(!filter.Word.IsNullOrWhiteSpace(), x => x.Word.Contains(filter.Word))
                        .WhereIf(filter.IsFavorited.HasValue, x => x.IsFavorited == filter.IsFavorited);

        }, filter).ProjectToPaginatedDataAsync<ChineseDictionary, ChineseDictionaryOutputModel>(
            filter.PageNumber,
            filter.PageSize,
            _mapper.ConfigurationProvider
        )).ToPageList();
    }

    /// <summary>
    /// 简繁体转换
    /// </summary>
    /// <param name="input">输入模型</param>
    /// <returns></returns>
    public async Task<ConvertChineseOutputModel> ConvertChineseAsync(ConvertChineseInputModel input)
    {
        return new ConvertChineseOutputModel
        {
            Word = await _dictionariesHelpers.ConvertChineseAsync(input.Word, input.isToSimplified),
            Description = await _dictionariesHelpers.ConvertChineseAsync(input.Description, input.isToSimplified),
        };     
    }

    /// <summary>
    /// 创建
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task CreateAsync(ChineseDictionaryCreateInputModel input)
    {
        var isExist = __chineseDictionaryRepository.Query(x => x.Word == input.Word).Any();
        ExceptionHelper.ThrowIfTrue(isExist, "词汇已存在");

        var model = _mapper.Map<ChineseDictionary>(input);
        model.Description = await _dictionariesHelpers.FetchWordDataFromSourceAsync(input.Word);
        await __chineseDictionaryRepository.InsertAsync(model);
    }

    /// <summary>
    /// 是否收藏
    /// </summary>
    /// <param name="id">唯一标识</param>
    /// <returns></returns>
    public async Task IsFavoritedAsync(long id)
    {
        await __chineseDictionaryRepository.UpdateAsync(x => x.SetProperty(p => p.IsFavorited, p => !p.IsFavorited), w => w.Id == id);
    }

    /// <summary>
    /// 删除
    /// </summary>
    /// <param name="ids">唯一标识，多个使用英文状态下的逗号（,）隔开</param>
    /// <returns></returns>
    public async Task DeleteAsync(string ids)
    {
        ExceptionHelper.ThrowIfNull(ids, "删除的唯一标识不能为空");

        List<long> idsToDelste = ids
            .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)  // 分割字符串
            .Select(id =>
            {
                if (long.TryParse(id.Trim(), out long result))
                {
                    return result;
                }
                else
                {
                    ExceptionHelper.ThrowIfTrue(true, "无效的标识");
                    return 0;
                }
            }).ToList();

        await __chineseDictionaryRepository.DeleteAsync(x => idsToDelste.Contains(x.Id));
    }
}
